package com.ken.common.web.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 自定义的异步线程池
 */
@Configuration
@Slf4j
public class AsyncExecutorConfig {

    @Autowired
    private AsyncExecurityConfiguration asyncExecurityConfiguration;

    /**
     * 自定义线程池参数
     * @return
     */
    @Bean
    @Primary
    @ConditionalOnBean(annotation = EnableAsync.class)
    public Executor getAsyncExecutor(){
        log.debug("[Async-Executor-init] - 线程池初始化 - {}", asyncExecurityConfiguration);
        //创建线程池包装对象
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //设置线程池参数
        taskExecutor.setCorePoolSize(asyncExecurityConfiguration.getCoreNum());//核心线程数
        taskExecutor.setMaxPoolSize(asyncExecurityConfiguration.getMaxNum());//最大线程数
        taskExecutor.setKeepAliveSeconds(asyncExecurityConfiguration.getMaxTimeoutSec());//空闲线程的最大存活时间
        taskExecutor.setAllowCoreThreadTimeOut(asyncExecurityConfiguration.isAllowCoreThreadTimeOut());//是否允许核心线程超时
        taskExecutor.setRejectedExecutionHandler(asyncExecurityConfiguration.getRejectHandler().getRejectedExecutionHandler());//设置拒绝策略
        taskExecutor.setThreadNamePrefix(asyncExecurityConfiguration.getThreadNamePrefix());//设置线程名称的前缀
        taskExecutor.setQueueCapacity(asyncExecurityConfiguration.getQueueCapacity());//阻塞队列的最大容量
        taskExecutor.initialize();
        return taskExecutor;
    }
}
